﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Portal.Cms.Bussiness.Template;
using Portal.Core;
using Portal.Web.Utility;
using System.Collections;
using System.Reflection;
using System.Data;
using Portal.Cms.Model;
using Portal.Web.Model;
using System.Collections.ObjectModel;
using Portal.Workflow.Bussiness;
using Portal.Workflow.Utilities;


namespace Portal.Cms.Utility
{
    public class CmsUtility
    {
        private static ICmsBussinessProcess[] LoadAssembly(string filename)
        {
            ArrayList ArrayListModules = new ArrayList();
            Assembly a = Assembly.LoadFrom(filename);
            if (a == null) throw new Exception("Assembly " + filename + " not found or not valid");
            foreach (Module mod in a.GetLoadedModules())
            {
                foreach (Type ty in mod.GetTypes())
                {
                    foreach (Type intf in ty.GetInterfaces())
                    {
                        if (intf == typeof(ICmsBussinessProcess))
                        {
                            ICmsBussinessProcess w = (ICmsBussinessProcess)a.CreateInstance(ty.FullName);
                            ArrayListModules.Add(w);
                        }
                    }
                }
            }
            ICmsBussinessProcess[] ws = new ICmsBussinessProcess[ArrayListModules.Count];
            for (int iIndex = 0; iIndex < ArrayListModules.Count; iIndex++)
            {
                ws[iIndex] = (ICmsBussinessProcess)ArrayListModules[iIndex];
            }
            return ws;
        }


        public static ICmsBussinessProcess[] LoadPlugIn(string SiteId)
        {
            SiteParam oSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string Path = oSiteParam.DllPath;
            string[] Files = System.IO.Directory.GetFiles(Path, "*.dll");
            ArrayList ArrayListServives = new ArrayList();
            for (int iIndex = 0; iIndex < Files.Length; iIndex++)
            {
                try
                {
                    string FileDll = Files[iIndex];
                    ICmsBussinessProcess[]
                        asms = LoadAssembly(FileDll);
                    for (int jIndex = 0; jIndex < asms.Length; jIndex++)
                    {
                        ArrayListServives.Add(asms[jIndex]);
                    }
                }
                catch (Exception ex)
                {
                    ex.Source = "";
                }
            }
            ICmsBussinessProcess[] WebParts = new ICmsBussinessProcess[ArrayListServives.Count];
            for (int iIndex = 0; iIndex < ArrayListServives.Count; iIndex++)
            {
                WebParts[iIndex] = (ICmsBussinessProcess)ArrayListServives[iIndex];
            }

            return WebParts;
        }


        public static ICmsBussinessProcess Find(string SiteId, string ServiceId)
        {
            ICmsBussinessProcess[] found = LoadPlugIn(SiteId);
            for (int iIndex = 0; iIndex < found.Length; iIndex++)
            {
                if (found[iIndex].Id != null)
                {
                    if (found[iIndex].Id.Trim().ToLower().Equals(ServiceId.Trim().ToLower()))
                    {
                        return found[iIndex];
                    }
                }
            }
            return null;
        }

        public static ICmsBussinessProcess CreateCmsBussinessProcess(string SiteId)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            OSiteParam.XmlConfigFile = OSiteParam.PathRoot + "\\xml\\siteconfig.xml";
            OSiteParam.VirtualHttpRoot = OSiteParam.MediaHttpRoot;
            string CmsBussinessProcessId = WebConfig.GetConfigFromXml(OSiteParam, "CmsBussinessProcessId");
            if (string.IsNullOrEmpty(CmsBussinessProcessId))
            {
                CmsBussinessProcessId = "SqlCmsBussinessProcess";
            }
            ICmsBussinessProcess CmsBussinessProcess = Find(SiteId, CmsBussinessProcessId);
            if (CmsBussinessProcess == null) throw new Exception("Không tìm thấy dịch vụ " + CmsBussinessProcessId);
            return CmsBussinessProcess;
        }

        public static void ServerSideStartWorkflow(
            IDbTransaction Trans,
            string SiteId,
            string WorkflowDefId,
            string CmsDataId,
            string CommandAction,
            string ObjectType,
            string AppendTitle)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string GroupBatchId = System.Guid.NewGuid().ToString();
            string BatchId = System.Guid.NewGuid().ToString();
            
            CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(Trans, SiteId, CmsDataId);
            if (OCmsData.IsPublic == 1) throw new Exception("Tin đã được phát hành không khởi tạo quy trình được!");

            bool HasStarted = WorkflowUtilities.CheckHasStartWorkflow(SiteId, CmsDataId);
            if (HasStarted) throw new Exception("Đã phát hành quy trình rồi! Xin vui lòng thực hiện trong quy trình");

            string ItemSubject = OCmsData.Subject;
            if (!string.IsNullOrEmpty(AppendTitle))
            {
                ItemSubject = ItemSubject + " (" + AppendTitle + ")";
            }
           
            WorkflowUtilities.StartWorkflow(
                Trans,
                SiteId,
                WorkflowDefId,
                WebSessionUtility.GetCurrentLoginUser().AssetCode,
                CmsDataId,
                WebSessionUtility.GetCurrentLoginUser().RoleId,
                GroupBatchId,
                BatchId,
                WebSessionUtility.GetCurrentLoginUser().LoginName,
                WebSessionUtility.GetCurrentLoginUser().FullName,
                ItemSubject,
                ObjectType,
                "");

            //goi cai nhet vao trong gi do
            WorkflowStartPluginMan.ExecuteStartPluginMan(Trans, OSiteParam, "CmsData", CmsDataId, OCmsData, CommandAction);
        }




        public static void ServerSideStartWorkflowUnPublishing(
           IDbTransaction Trans,
           string SiteId,
           string WorkflowDefId,
           string CmsDataId,
           string CommandAction,
           string ObjectType,
           string AppendTitle)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string GroupBatchId = System.Guid.NewGuid().ToString();
            string BatchId = System.Guid.NewGuid().ToString();

            CmsDataCls OCmsData = CmsUtility.CreateCmsBussinessProcess(SiteId).CreateCmsProcess(SiteId).CreateCmsDataModel(Trans, SiteId, CmsDataId);
            if (OCmsData.IsPublic == 0) throw new Exception("Tin đã gỡ phát hành không khởi tạo quy trình được!");

            bool HasStarted = WorkflowUtilities.CheckHasStartWorkflow(SiteId, CmsDataId);
            if (HasStarted) throw new Exception("Đã phát hành quy trình rồi! Xin vui lòng thực hiện trong quy trình");

            string ItemSubject = OCmsData.Subject;
            if (!string.IsNullOrEmpty(AppendTitle))
            {
                ItemSubject = ItemSubject + " (" + AppendTitle + ")";
            }

            WorkflowUtilities.StartWorkflow(
                Trans,
                SiteId,
                WorkflowDefId,
                WebSessionUtility.GetCurrentLoginUser().AssetCode,
                CmsDataId,
                WebSessionUtility.GetCurrentLoginUser().RoleId,
                GroupBatchId,
                BatchId,
                WebSessionUtility.GetCurrentLoginUser().LoginName,
                WebSessionUtility.GetCurrentLoginUser().FullName,
                ItemSubject,
                ObjectType,
                "");

            //goi cai nhet vao trong gi do
            WorkflowStartPluginMan.ExecuteStartPluginMan(Trans, OSiteParam, "CmsData", CmsDataId, OCmsData, CommandAction);
        }
    }
}
